import { readBody, defineEventHandler } from 'h3'
import redis from '../util/redis'
import { recordLog } from '../util/log'

// POST /api/clipboard
// body: { key: string, value: string, expireSeconds?: number }
export default defineEventHandler(async (event) => {
  try {
    const body = await readBody(event) as any
    const key = body?.key ?? ''
    const value = body?.value ?? ''
    let expireSeconds = Number(body?.expireSeconds ?? 0)

    if (!key || typeof key !== 'string') {
      event.node.res.statusCode = 400
      return { status: 400, message: 'missing key' }
    }

    if (typeof value !== 'string' || value.length === 0) {
      event.node.res.statusCode = 400
      return { status: 400, message: 'missing value' }
    }

    // Max expire 7 days
    const maxSeconds = 7 * 24 * 3600
    if (!Number.isFinite(expireSeconds) || expireSeconds <= 0) {
      // default 1 day
      expireSeconds = 24 * 3600
    }
    if (expireSeconds > maxSeconds) expireSeconds = maxSeconds

    try {
      // Use EX to set expiry in seconds
      await (redis as any).set(key, value, 'EX', expireSeconds)
      await recordLog(event as any, { message: `clipboard: saved key=${key} expire=${expireSeconds}s`, userId: 0 })
      return { status: 'ok', key, expireSeconds }
    } catch (err: any) {
      event.node.res.statusCode = 500
      await recordLog(event as any, { message: `clipboard: redis set failed ${String(err)}`, userId: 0 })
      return { status: 500, message: 'redis set failed', error: String(err) }
    }
  } catch (err: any) {
    event.node.res.statusCode = 500
    await recordLog(event as any, { message: `clipboard: internal error ${String(err)}`, userId: 0 })
    return { status: 500, message: 'internal error', error: String(err) }
  }
})
